package com.hjw.exer;

/**
 * 商品信息类，实现对商品信息的管理。
 * @author hjwStrart
 * @create 2022-01-07 16:24
 */
public class CommodityOperation {
    private Commodity[] commodities;
    private static Integer count = 0;
    public CommodityOperation(){

    }

    public CommodityOperation(Commodity[] commodities) {
        this.commodities = commodities;
    }

    /**
     * 向数组中添加商品信息
     * @param commodity
     */
    public void addGoods(Commodity commodity){
        commodities[count] = commodity;
        count ++;
    }

    /**
     * 根据索引修改商品信息
     * @param index  要查询的商品索引
     * @return    商品索引
     */
    public void updateGoods(Integer index,Commodity commodity){
        Integer result = selectGoods(index);
        if (result == null) {
            System.out.println("该商品还未录入到系统中。。。");
        }else{
            commodities[index] = commodity;
        }
    }

    /**
     * 根据商品名搜索商品信息
     * @param name
     * @param commodity
     */
    public void updateGoods(String name,Commodity commodity){
        Integer index = selectGoods(name);
        if (index == null) {
            System.out.println("该商品还未录入到系统中。。。");
        }else{
            commodities[index] = commodity;
        }
    }
    /**
     * 根据索引查询商品
     * @param index
     * @return  null未查询到该商品，返回大于等于0，该元素在数组中的索引
     */
    public Integer selectGoods(Integer index){
        if (commodities[index] == null) {
            return null;
        }
        return index;
    }

    /**
     * 根据商品名返回索引
     * @param name 商品名
     * @return  大于等于0商品索引，null未查找给商品
     */
    public Integer selectGoods(String name){
        for (int i = 0; i < commodities.length; i++) {
            if (commodities[i] == null) break;
                if (commodities[i].getName().equals(name)) {
                    return i;
                }
        }
        return null;
    }

    /**
     * 删除指定位置的元素，并将后面的元素前移一位
     * @param index  所有删除的元素的索引
     */
    public void deleteGoods(Integer index){
        Integer result = selectGoods(index);
        if (result == null) {
            System.out.println("该商品不存在");
        }else{
            commodities[index] = null;
            forwardMoveArrElem(index + 1,commodities);
            count--;
        }
    }

    /**
     * 将数组从指定未开始前移一位
     * @param beginIndex  起点
     * @param t   数组
     * @param <T>  类型
     */
    public <T> void forwardMoveArrElem(Integer beginIndex,T[] t){
        if (beginIndex > t.length || beginIndex < 0)
            throw new StringIndexOutOfBoundsException(beginIndex);
        for (int i = beginIndex; i < t.length; i++) {
            t[i -1] = t[i];
        }
        t[t.length - 1] = null;
    }

    public void getAllCommoditiesInfo(){
        for (Commodity commodity : commodities) {
            if (commodity != null) {
                System.out.println(commodity);
            }
        }
    }
}
